#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "huffman.h"
#include "bf.h"

int main (int argc, char *argv[]) {
  int b, c;
  FILE *out;
  bf_stream in;
  huff_node curr;
  
  if (argc != 3) {
    fprintf (stderr, "usage: %s <inputfile> <outputfile>\n", argv[0]);
    exit (EXIT_FAILURE);
  }

  if (!strncmp (argv[2], "-", 2)) {
    out = stdout;
  } else if (!(out = fopen (argv[2], "w"))) {
    perror ("compress : error opening output file");
    exit (EXIT_FAILURE);
  }

  if (!strncmp (argv[1], "-", 2)) {
    if (!(in = bf_stream_new (0))) {
    perror ("compress : error opening input file");
    exit (EXIT_FAILURE);
    }
  } else if (!(in = bf_open (argv[1], BF_READ))) {
    perror ("compress : error opening input file");
    exit (EXIT_FAILURE);
  }

  c = bf_getchar (in);
  fputc (c, out);
  huff_tree_init (c);
  curr = thetree.root;
  
  while ((b = bf_getbit (in)) != EOF) {
    if (b == 0 && huff_node_isspecial (curr)) {
      c = bf_getchar (in);
      if (c == EOF) {
	curr = thetree.root;
	break;
      }
      fputc (c, out);
      huff_tree_modify (c);
      curr = thetree.root;
      continue;
    }
    curr = b ? curr->right : curr->left;
    if (huff_node_isleaf (curr)) {
      fputc (curr->c, out);
      huff_tree_modify (curr->c);
      curr = thetree.root;
    }
  }

  if (curr != thetree.root) {
    fprintf (stderr, "EOF encountered and only a part of a character was read!\n");
    exit (EXIT_FAILURE);
  }

  bf_close (in);
  fclose (out);
  return (EXIT_SUCCESS);
}
